package cn.xwlin.service;

import cn.xwlin.consts.Result;
import cn.xwlin.consts.TicketStatusConstant;
import cn.xwlin.entity.TicketInProgressInfo;
import cn.xwlin.entity.TicketRegion;
import cn.xwlin.mapper.TicketInProgressInfoMapper;
import cn.xwlin.mapper.TicketRegionMapper;
import cn.xwlin.util.HttpUtils;
import cn.xwlin.vo.CreateReq;
import cn.xwlin.vo.CreateResp;
import cn.xwlin.vo.RegionCacheInfo;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CreateMatchService {

    @Autowired
    private TicketRegionMapper ticketRegionMapper;
    @Autowired
    private TicketInProgressInfoMapper ticketInProgressInfoMapper;

    LoadingCache<Long, RegionCacheInfo> ticketRegionCache = CacheBuilder.newBuilder().maximumSize(70) // maximum 100 records can be cached
            .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access
            .build(new CacheLoader<Long, RegionCacheInfo>() {
                @Override
                public RegionCacheInfo load(Long uuid) throws Exception {
                    return getFromDatabase(uuid);
                }
            });

    @Transactional
    public Result createMatch(Long ticketInProgressInfoId, Long ticketRegionUuid) {
        TicketInProgressInfo ticketInProgressInfo = ticketInProgressInfoMapper.selectByPrimaryKey(ticketInProgressInfoId);
        if (ticketInProgressInfo == null) {
            return Result.failure("没有找到数据");
        }
        TicketInProgressInfo updateDb = new TicketInProgressInfo();
        updateDb.setId(ticketInProgressInfo.getId());
        if (!StringUtils.hasLength(ticketInProgressInfo.getViewInfo())) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 30000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
            return Result.failure(ticketInProgressInfo.getUserId() + ",没有观赛人信息");
        }
        if (!ticketInProgressInfo.getStatus().equalsIgnoreCase(TicketStatusConstant.STATUS_IN_PROGRESS)) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 30000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
            return Result.failure(ticketInProgressInfo.getUserId() + ",状态不=2");
        }
        if (!StringUtils.hasLength(ticketInProgressInfo.getRegionInfo())) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 30000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
            return Result.failure(ticketInProgressInfo.getUserId() + "," + ticketInProgressInfo.getRegionInfo() + " no " + ticketRegionUuid);
        }
        if (!ticketInProgressInfo.getRegionInfo().contains(ticketRegionUuid.toString())) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 3000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
            return Result.failure(ticketInProgressInfo.getUserId() + "," + ticketInProgressInfo.getRegionInfo() + " no " + ticketRegionUuid);
        }

        RegionCacheInfo regionCacheInfo;
        try {
            regionCacheInfo = ticketRegionCache.get(ticketRegionUuid);
        } catch (Exception e) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 30000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
            return Result.failure(ticketInProgressInfo.getUserId() + ",获取作为缓存数据失败");
        }
        List<CreateReq.User> users = JSONArray.parseArray(ticketInProgressInfo.getViewInfo(), CreateReq.User.class);

        CreateReq.Region region = new CreateReq.Region();
        region.setNum(users.size());
        region.setRegion(regionCacheInfo.getRegion());
        region.setEstate(regionCacheInfo.getEstate());
        region.setName(regionCacheInfo.getName());
        region.setPrice(regionCacheInfo.getPrice());
        region.setUsableCount(regionCacheInfo.getUsableCount());
        CreateReq createReq = new CreateReq(regionCacheInfo.getMatchId(), region, users);
        String matchOrder = HttpUtils.createMatchOrder(ticketInProgressInfo.getUserId(), ticketInProgressInfo.getLoginCode(), ticketInProgressInfo.getLoginToken(), JSON.toJSONString(createReq), ticketInProgressInfo.getHeaderInfo());
        System.out.println("###下单响应#" + ticketInProgressInfo.getUserId() + "#" + region.getName() + "#:" + matchOrder);
        if (!StringUtils.hasLength(matchOrder)) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 3000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
            return Result.failure("下单返回失败，为空");
        }

        CreateResp userResponse = JSONObject.parseObject(matchOrder, CreateResp.class);
        // 成功了，通知创建成功
        if (userResponse.getCode() != null && userResponse.getCode() == 1) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 600000));
            updateDb.setSuccessData(userResponse.getData());
            updateDb.setStatus(TicketStatusConstant.STATUS_SUCCESS);
            updateDb.setSuccessTime(new Date());
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
            // 发送通知
            HttpUtils.sendNotice(ticketInProgressInfo.getUserId());
            return Result.success(ticketInProgressInfo.getUserId(), userResponse.getData());
        }
        // 这里失败，去判断失败的问题，看有没有有效文案
        if (!StringUtils.hasLength(userResponse.getMsg())) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 3000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
        }
        if (userResponse.getMsg().contains("门票数量不足")) {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 3000));
            updateDb.setLastestFailedValidTime(new Date());
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
        } else {
            updateDb.setNextCheckTime(new Date(System.currentTimeMillis() + 3000));
            ticketInProgressInfoMapper.createMatchOrderToUpdate(updateDb);
        }
        return Result.failure(ticketInProgressInfo.getUserId() + "," + userResponse.getMsg());
    }

    private RegionCacheInfo getFromDatabase(Long uuid) {
        TicketRegion ticketRegion = ticketRegionMapper.selectByPrimaryKey(uuid);
        if (ticketRegion == null) {
            return null;
        }
        RegionCacheInfo regionCacheInfo = new RegionCacheInfo();
        regionCacheInfo.setMatchId(ticketRegion.getMatchId());
        regionCacheInfo.setRegion(ticketRegion.getRegion());
        regionCacheInfo.setEstate(ticketRegion.getEstate());
        regionCacheInfo.setName(ticketRegion.getName());
        regionCacheInfo.setPrice(ticketRegion.getPrice());
        regionCacheInfo.setUsableCount(ticketRegion.getUsableCount());
        return regionCacheInfo;
    }
}
